package com.flex.reflection.tokenizer;

import com.flex.reflection.MetaClass;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author ganlt
 * @since 2019/09/24 13:39
 */
public class StringSimpleExpression implements Expression {
    private BindExpressionHandler bindExpressionHandler;
    private String variableTagStart = "{";
    private String variableTagEnd = "}";

    @Override
    public Object resolver(String expression, MetaClass reflector) {
        PropertyTokenizer tokenizer = new PropertyTokenizer(expression);
        String name = getVariable(tokenizer.getName());
        String indexFlag = getVariable(tokenizer.getIndex());
        Object obj = reflector.invokeGetField(name);
        Object result = obj;
        do  {
            if (obj instanceof List || obj instanceof Set) {
                Integer index = Integer.parseInt(indexFlag);
                List<Object> tmpList = new ArrayList<>((List) obj);
                result = tmpList.get(index);
            } else if (obj instanceof Map) {
                String index = indexFlag;
                if (StringUtils.isNumeric(index)) {
                    Integer indexInt = Integer.parseInt(index);
                    Set keys = ((Map) obj).keySet();
                    int temIndex = 0;
                    for (Object key : keys) {
                        if (temIndex++ == indexInt) {
                            result = ((Map) obj).get(key);
                        }
                    }
                } else {
                    result = ((Map) obj).get(index);
                }
            } else if (obj.getClass().isArray()){
                Integer index = Integer.parseInt(indexFlag);
                result = ((Object[])obj)[index];
            }
            if (!tokenizer.hasNext()) {
                return result;
            }

            return resolver(tokenizer.getChildren(), MetaClass.of(result).build());
        } while ((tokenizer.hasNext()));


    }

    private String getVariable(String name) {
        if (name == null) {
            return null;
        }
        if (bindExpressionHandler!= null) {
            if (name.startsWith(variableTagStart)) {
                String removeLabelName = name.replace(variableTagStart,"").replace(variableTagEnd,"");
                String finalName = bindExpressionHandler.toBind(removeLabelName);
                return finalName;
            }
        }
        return name;
    }

    public void setExpressionHandler(BindExpressionHandler handler){
        this.bindExpressionHandler = handler;
    }
}
